import Koa from 'koa';
import { koaBody } from 'koa-body';
import cors from '@koa/cors';
import serve from 'koa-static';
import { join } from 'path';
import { uploadRouter } from './routes/upload.js';
import { errorHandler } from './middleware/error-handler.js';
import { ensureDirSync } from 'fs-extra';
import { UPLOAD_DIR, PORT, __dirname } from './config/constants.js';

// Ensure upload directory exists
ensureDirSync(UPLOAD_DIR);

const app = new Koa();

// Global error handler
app.use(errorHandler);

// Middleware
app.use(cors());
app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: UPLOAD_DIR,
    keepExtensions: true,
    maxFileSize: 200 * 1024 * 1024 // 200MB limit
  }
}));

// Serve static files from public directory
app.use(serve(join(__dirname, '../../public')));

// Routes
app.use(uploadRouter.routes());
app.use(uploadRouter.allowedMethods());

app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
  console.log(`Files will be uploaded to: ${UPLOAD_DIR}`);
});
